import json
import pandas as pd
import re
from functools import partial
from control.Databasemanage import DatabaseManager
from control.SystemSet import SystemSet
from threadmange.scoringThread import ScoringThread
from threadmange.selectThread import SelectThread
from view import homePage
from PyQt5.QtWidgets import QSizePolicy, QMainWindow, QHeaderView, QAbstractItemView, QTableWidget, QTableWidgetItem, \
    QPushButton, QCheckBox, QHBoxLayout, QWidget, QFileDialog, QMessageBox, QLabel
from test_api import getdir
from PyQt5.QtGui import QIcon, QColor, QFont, QPixmap
from control.Select import Select
from PyQt5.QtCore import QTimer, Qt, QThread, pyqtSignal

db_manager = DatabaseManager()
db_manager.connect()
cursor = db_manager.connection.cursor()

class HomePage(homePage.Ui_MainWindow, QMainWindow):
    def __init__(self):
        super(HomePage, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("电子化阅卷系统自动阅卷终端")
        self.setWindowIcon(QIcon(getdir() + "image/dl_image2.png"))  # 添加标题栏图标
        self.pushButton_21.clicked.connect(self.select)
        self.pushButton_23.clicked.connect(self.database_set)
        self.pushButton_22.clicked.connect(self.began_rj)  # 开始阅卷
        self.pushButton_25.clicked.connect(self.ckxf)  # 查看详分
        self.pushButton_24.clicked.connect(self.save_csv) #导出
        self.pushButton_27.clicked.connect(self.reset)
        self.lineEdit_4.setPlaceholderText('请输入关键词')
        self.lineEdit_4.returnPressed.connect(self.fuzzy_search)
        self.items_per_page = int(self.comboBox_10.currentText())
        self.total_nums = 0
        self.total_pages = 0
        self.page_number = 1
        self.comboBox_10.currentIndexChanged.connect(self.updateTableRowCount)
        # 设置分页按钮的信号连接
        self.pushButton_35.clicked.connect(lambda: self.changePage(0))
        self.pushButton_40.clicked.connect(lambda: self.changePage(1))
        self.pushButton_43.clicked.connect(lambda: self.changePage(2))
        self.pushButton_34.clicked.connect(self.previousPage)
        self.pushButton_44.clicked.connect(self.nextPage)
        self.Init()
        self.page_number = 1
        self.rows_per_page = int(self.comboBox_10.currentText())
        self.lineEdit_6.returnPressed.connect(self.on_enter_pressed)
        self.lineEdit_6.textChanged.connect(self.on_text_changed)
        self.lineEdit_6.adjustSize()
        self.now_data = []
        self.detail_data = []
        self.results_data = []
        # 加载图片
        self.pixmapT = QPixmap(getdir() + 'resources/dui.png')  # 替换为您的图片路径
        self.pixmapF = QPixmap(getdir() + 'resources/close-l.png')  # 替换为您的图片路径

        self.cn2en = {
            "序号": "tId",
            "科目代码": "subject_code",
            "科目名称": "subject_name",
            "考题": "answer_qr_code",
            "考生号": "student_id",
            "姓名": "student_name",
            "小题数": "child_num",
            "阅卷状态": "split_answer_status",
            "总分": "answer_score",
            "得分": "total_score",
            "复阅状态": "STATE",
            "阅卷时间": "modify_time",
            "操作": "operation",
            "详情": "details"
        }

        self.cn2en1 = {
            "序号": "tId",
            "科目代码": "subject_code",
            "科目名称": "subject_name",
            "考题": "answer_qr_code",
            "考生号": "student_id",
            "姓名": "student_name",
            "小题号": "answer_no",
            "参考答案": "answer_standard",
            "识别值": "answer_student",
            "评价结果": "evaluate_results",
            "满分": "answer_score",
            "得分": "get_score",
            "复阅状态": "STATE",
            "阅卷时间": "modify_time"
        }

        self.bcolor = "rgba(61, 110, 215, 64);"

        self.comboBox_2.currentTextChanged.connect(self.selectquestion)

        self.addsubject()
        self.setup_UI_timer()
        self.setupComboBox()
        self.initialization(mode=0)

    def addsubject(self):
        # 准备字典来存储 subject_code 和 subject_name 的映射关系
        cursor.execute("SELECT subject_code, subject_name FROM exam_subject")
        rows = cursor.fetchall()

        # # 清空下拉框
        # self.comboBox_10.clear()

        # 处理查询结果并添加到下拉框
        for row in rows:
            subject_code, subject_name = row
            item_text = f"({subject_code}) {subject_name}"
            # print(row)
            self.comboBox_2.addItem(item_text)

    def selectquestion(self):
        subject = self.comboBox_2.currentText()

        if subject != "请选择科目":
            # 使用正则表达式匹配括号内的内容
            # 这里的正则表达式匹配最外层的括号内的内容
            match = re.search(r'\(([^)]+)\)', subject)

            subject_code = match.group(1)
            # 准备字典来存储 subject_code 和 subject_name 的映射关系
            cursor.execute("SELECT answer_qr_code FROM exam_scan_split WHERE subject_code = ?", (subject_code,))
            rows = cursor.fetchall()

            # 创建一个空集合来存储结果，自动去重
            unique_answer_qr_codes = set()

            # 遍历查询结果
            for row in rows:
                # 假设每行的结构是 (answer_qr_code,)
                answer_qr_code = row[0]

                # 将结果添加到集合中，自动去重
                unique_answer_qr_codes.add(answer_qr_code)

            # 打印去重后的结果
            for question in list(unique_answer_qr_codes):
                # 提取第一位和第二位
                question_type = question[0]  # 第一位代表题目类型
                section_number = question[1]  # 第二位代表大题号
                if question_type == "1":
                    question_type = "单选题"
                elif question_type == "2":
                    question_type = "多选题"
                elif question_type == "3":
                    question_type = "判断题"

                # 转换第二位为中文大写数字
                converted_section_number = self.convert_section_number(section_number)

                # 组合新的值
                new_value = f"{converted_section_number}、{question_type}"
                self.comboBox_3.addItem(new_value)
        else:
            self.comboBox_3.clear()

    def save_csv(self):
        # 打开文件对话框
        options = QFileDialog.Options()
        file_path, _ = QFileDialog.getSaveFileName(self, "Save CSV File", "", "CSV Files (*.csv);;All Files (*)",
                                                   options=options)
        if file_path:
            # 创建示例数据
            df = pd.DataFrame(self.now_data, columns=list(self.cn2en.keys()))
            # 保存到指定路径
            try:
                df.to_csv(file_path, index=False)
                QMessageBox.information(self.mainwindos, "成功", "导出结果成功！")
            except Exception as e:
                QMessageBox.critical(self.mainwindos, "Error", f"导出结果失败:\n{e}")

    def on_text_changed(self):
        cur_value = self.lineEdit_6.text()
        if cur_value is not None and cur_value != "":
            # 通过100限制输入框的最大长度
            self.lineEdit_6.setMinimumWidth(min(200, max(30, 10 * len(str(cur_value)))))
            self.lineEdit_6.setMaximumWidth(min(200, max(30, 10 * len(str(cur_value)))))

    def on_enter_pressed(self):
        cur_value = self.lineEdit_6.text()
        if cur_value.isdigit():
            cur_value = int(cur_value)
            if 1 <= cur_value <= self.total_pages:
                self.page_number = cur_value
                if cur_value <= self.total_pages - 2 or self.total_pages == 1:
                    self.pushButton_35.setText(str(cur_value))
                    self.pushButton_40.setText(str(cur_value + 1))
                    self.pushButton_43.setText(str(cur_value + 2))
                elif cur_value == self.total_pages - 1 or self.total_pages == 2:
                    self.pushButton_35.setText(str(cur_value - 1))
                    self.pushButton_40.setText(str(cur_value))
                    self.pushButton_43.setText(str(cur_value + 1))
                elif cur_value == self.total_pages:
                    self.pushButton_35.setText(str(cur_value - 2))
                    self.pushButton_40.setText(str(cur_value - 1))
                    self.pushButton_43.setText(str(cur_value))
                self.check_right_left()
                self.check_three()
                self.updateTable()
                # self.lineEdit_6.setText("")
            else:
                QMessageBox.information(self, "错误", f"请选择正确的索引值（1~{str(self.total_pages)}）")
        else:
            QMessageBox.information(self, "错误", f"请选择正确的索引值（1~{str(self.total_pages)}）")
        self.lineEdit_6.clear()
        self.lineEdit_6.setMinimumWidth(max(30, 10 * len(str(cur_value))))
        self.lineEdit_6.setMaximumWidth(max(30, 10 * len(str(cur_value))))

    # 修改 HomePage 类中的 ckxf 方法
    def ckxf(self):
        items_per_page = int(self.comboBox_10.currentText())
        page_number = self.page_number
        self.detailed_scores_thread = DetailThread(page_number, items_per_page, self)
        self.detailed_scores_thread.detail_data_signal.connect(self.update_detail_data)
        self.detailed_scores_thread.start()

    def update_detail_data(self, detail_data, total_pages, total_count):
        self.detail_data = detail_data
        self.results_data = []
        for index, entry in enumerate(self.detail_data, start=1):
            row = [str((self.page_number - 1) * self.items_per_page + index)]  # 序号
            # 使用 self.cn2en1 提取相应的值
            for key in list(self.cn2en1.keys())[1:]:  # 从第二个键开始，因为第一个是序号
                row.append(str(entry.get(str(self.cn2en1[key]), " ")))  # 以字符串显示
            self.results_data.append(row)

        self.total_pages = total_pages
        self.total_count = total_count
        self.label_12.setText(f"共{self.total_count}条/{self.total_pages}页")

        self.initialization(mode=1)
        self.stackedWidget.setCurrentIndex(0)
        self.pushButton_25.setText("返回")
        # 更改按钮功能，连接到新的槽函数
        self.pushButton_25.clicked.disconnect()  # 断开原来的连接
        self.pushButton_25.clicked.connect(self.goBack)  # 连接到新的槽函数

    def goBack(self):
        self.initialization(mode=0)
        self.stackedWidget.setCurrentIndex(1)
        self.pushButton_25.setText("查看详分")
        # 更改按钮功能，连接到新的槽函数
        self.pushButton_25.clicked.disconnect()  # 断开原来的连接
        self.pushButton_25.clicked.connect(self.ckxf)  # 连接到新的槽函数

    def Init(self):
        self.comboBox_4.addItem("未阅")
        self.comboBox_4.addItem("已完成")
        self.comboBox_4.addItem("已阅失败")
        self.comboBox_5.addItem("未复阅")
        self.comboBox_5.addItem("已复阅")
        self.comboBox_5.addItem("复阅不一致")

    def setup_UI_timer(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.setupUI)
        self.timer.start(10)  # 每10ms检查一次

    def setupUI(self):
        self.adjust_column_width()
        # # 设置行距自适应
        self.tableWidget_2.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def adjust_column_width(self):
        total_table_width = self.tableWidget_2.width()
        column_count = self.tableWidget_2.columnCount()

        # 先自适应每列
        for column in range(column_count):
            self.tableWidget_2.resizeColumnToContents(column)

        # 计算每列的宽度总和
        total_column_width = sum(self.tableWidget_2.columnWidth(column) for column in range(column_count))

        # 设置最大宽度
        max_width = 1000

        # 计算比例因子
        if total_column_width > 0:
            scale_factor = total_table_width / total_column_width

            # 计算新的列宽并应用
            new_widths = []
            for column in range(column_count):
                new_width = int(self.tableWidget_2.columnWidth(column) * scale_factor)
                new_width = min(new_width, max_width)  # 确保不超过最大宽度
                new_widths.append(new_width)

            # 计算新的总宽度
            adjusted_total_width = sum(new_widths)

            # 调整列宽以消除空白
            if adjusted_total_width < total_table_width:
                difference = total_table_width - adjusted_total_width
                # 将差值均匀分配到每列
                for i in range(column_count):
                    new_widths[i] += int(difference / column_count)

            # 设置新的列宽
            for column in range(column_count):
                self.tableWidget_2.setColumnWidth(column, new_widths[column])

            # 重新检查总宽度是否与表格宽度一致
            final_total_width = sum(self.tableWidget_2.columnWidth(column) for column in range(column_count))
            if final_total_width < total_table_width:
                # 如果仍然小于，补充剩余的空间到最后一列
                self.tableWidget_2.setColumnWidth(column_count - 1,
                                                           self.tableWidget_2.columnWidth(column_count - 1) + (
                                                                       total_table_width - final_total_width))
        self.tableWidget_2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        total_table_width1 = self.tableWidget.width()
        column_count1 = self.tableWidget.columnCount()
        # 先自适应每列
        for column in range(column_count1):
            self.tableWidget.resizeColumnToContents(column)

        # 计算每列的宽度总和
        total_column_width1 = sum(self.tableWidget.columnWidth(column) for column in range(column_count1))

        # 设置最大宽度
        max_width = 1000

        # 计算比例因子
        if total_column_width1 > 0:
            scale_factor = total_table_width1 / total_column_width1

            # 计算新的列宽并应用
            new_widths = []
            for column in range(column_count1):
                new_width = int(self.tableWidget.columnWidth(column) * scale_factor)
                new_width = min(new_width, max_width)  # 确保不超过最大宽度
                new_widths.append(new_width)

            # 计算新的总宽度
            adjusted_total_width1 = sum(new_widths)

            # 调整列宽以消除空白
            if adjusted_total_width1 < total_table_width1:
                difference = total_table_width1 - adjusted_total_width1
                # 将差值均匀分配到每列
                for i in range(column_count1):
                    new_widths[i] += int(difference / column_count1)

            # 设置新的列宽
            for column in range(column_count1):
                self.tableWidget.setColumnWidth(column, new_widths[column])

            # 重新检查总宽度是否与表格宽度一致
            final_total_width1 = sum(self.tableWidget.columnWidth(column) for column in range(column_count1))
            if final_total_width1 < total_table_width1:
                # 如果仍然小于，补充剩余的空间到最后一列
                self.tableWidget.setColumnWidth(column_count1 - 1,
                                                           self.tableWidget.columnWidth(column_count1 - 1) + (
                                                                       total_table_width1 - final_total_width1))
        self.tableWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)


    def setupComboBox(self):
        self.comboBox_10.currentIndexChanged.connect(self.updateTableRowCount)

    def updateTableRowCount(self):
        row_count = int(self.comboBox_10.currentText())
        self.items_per_page = row_count
        self.rows_per_page = row_count
        self.tableWidget_2.setRowCount(row_count + 1)  # row_count + 1的原因是除开第一行的表头
        self.initialization(mode=0)

    def database_set(self):
        self.next_page = SystemSet()
        self.next_page.show()

    def fuzzy_search(self):
        self.page_number = 1  # 类似于刷新一次
        self.update_data()
        self.lineEdit_4.setPlaceholderText('请输入关键词')

    def began_rj(self):
        if self.comboBox_2.currentText() == "请选择科目":
            QMessageBox.critical(self, "错误", "请先选择科目")
        elif self.comboBox_3.currentText() == "选择阅卷答题":
            QMessageBox.critical(self, "错误", "请选择小题")
        else:
            self.rjjd = Select(self)
            self.rjjd.show()

    def convert_section_number(self, section_number):
        # 将数字转换为中文大写数字
        chinese_numbers = {
            '1': '一', '2': '二', '3': '三', '4': '四',
            '5': '五', '6': '六', '7': '七', '8': '八',
            '9': '九', '10': '十'
        }
        return chinese_numbers.get(section_number, '')

    def convert_chinese_to_arabic(self, chinese_number):
        # 将中文数字转换为阿拉伯数字
        chinese_to_arabic = {
            '一': '1', '二': '2', '三': '3', '四': '4',
            '五': '5', '六': '6', '七': '7', '八': '8',
            '九': '9', '十': '10'
        }
        return chinese_to_arabic.get(chinese_number, '0')



    def detailed_scores(self):
        # 准备字典来存储 subject_code 和 subject_name 的映射关系
        cursor.execute("SELECT subject_code, subject_name FROM exam_subject")
        subject_dict = {row[0]: row[1] for row in cursor.fetchall()}

        cursor.execute("SELECT student_id, student_name FROM student_info")
        student_dic = {row[0]: row[1] for row in cursor.fetchall()}

        cursor.execute("SELECT answer_id, answer_no, answer_qr_code FROM exam_answer_into")
        small_question_dic = {row[0]: (row[1], row[2]) for row in cursor.fetchall()}

        cursor.execute("SELECT paper_id, subject_code, student_id, answer_id, answer_standard, answer_student, answer_score, modify_time FROM exam_scan_split_answer")
        rows = cursor.fetchall()
        for row in rows:
            if row[7] is not None:
                row[7] = row[7].strftime('%Y-%m-%d %H:%M:%S')
            elif row[7] is None:
                row[7] = " "

        # 字段名列表
        field_names = [
            "paper_id", "subject_code", "student_id", "answer_id", "answer_standard", "answer_student", "answer_score", "modify_time",
            "subject_name", "student_name", "answer_no", "answer_qr_code", "evaluate_results", "get_score"
        ]

        # 步骤 2: 使用每个 row 的 subject_code 去第二个表里查对应的 subject_name 并添加到每个 row 里
        new_rows = []
        for row in rows:
            subject_code = row[1]
            subject_name = subject_dict.get(subject_code, "Null")
            new_row = list(row) + [subject_name]  # 将 subject_name 添加到 row
            if new_row[5] == 0:
                new_row[5] = "未阅"
            elif new_row[5] == 1:
                new_row[5] = "已完成"
            elif new_row[5] == 2:
                new_row[5] = "已阅失败"
            new_rows.append(new_row)

        # 再次循环 new_rows 来添加 student_name 和 answer_score
        for new_row in new_rows:
            student_id = new_row[2]
            student_name = student_dic.get(student_id, "Null")
            answer_id = new_row[3]
            answer_no, answer_qr_code = small_question_dic.get(answer_id, "Null")
            student_row = new_row + [student_name, answer_no, answer_qr_code]

            if student_row[5] == student_row[4]:
                get_score = student_row[6]
                evaluate_results = "1"
            else:
                get_score = "0"
                evaluate_results = "0"

            finally_row = student_row + [evaluate_results, get_score]

            # 提取第一位和第二位
            question_type = finally_row[11][0]  # 第一位代表题目类型
            section_number = finally_row[11][1]  # 第二位代表大题号
            if question_type == "1":
                question_type = "单选题"
            elif question_type == "2":
                question_type = "多选题"
            elif question_type == "3":
                question_type = "判断题"

            # 转换第二位为中文大写数字
            converted_section_number = self.convert_section_number(section_number)

            # 组合新的值
            new_value = f"{converted_section_number}、{question_type}"
            finally_row[11] = new_value  # 更新 new_row[3] 的值

            # 创建一个字典来存储字段名和对应的值
            row_dict = dict(zip(field_names, finally_row))
            # print(row_dict)
            self.detail_data.append(row_dict)

        self.results_data = []
        for index, entry in enumerate(self.detail_data, start=1):
            row = [str((self.page_number - 1) * self.items_per_page + index)]  # 序号
            # 使用 self.cn2en1 提取相应的值
            for key in list(self.cn2en1.keys())[1:]:  # 从第二个键开始，因为第一个是序号
                row.append(str(entry.get(str(self.cn2en1[key]), " ")))  # 以字符串显示
            self.results_data.append(row)

    def select_data_first(self):
        items_per_page = int(self.comboBox_10.currentText())
        page_number = self.page_number
        self.select_data_first_thread = FirstDetailThread(page_number, items_per_page, self)
        self.select_data_first_thread.data_signal.connect(self.update_select_data_first)
        self.select_data_first_thread.start()

    def update_select_data_first(self, data, total_pages, total_count, scores_dict):
        self.now_data = data
        # 创建一个字典，以paper_id, subject_code, student_id, answer_id为键，total_score为值
        total_score_dict = {(ts['paper_id'], ts['subject_code'], ts['student_id'], ts['answer_id']): ts['total_score']
                            for ts in scores_dict}

        # 遍历students_info，如果键存在，则添加total_score
        for student in self.now_data:
            key = (student['paper_id'], student['subject_code'], student['student_id'], student['answer_id'])
            if key in total_score_dict:
                student['total_score'] = total_score_dict[key]
            else:
                student['total_score'] = 0

        self.results_data = []
        for index, entry in enumerate(self.now_data, start=1):
            row = [str((self.page_number - 1) * self.items_per_page + index)]  # 序号
            # 使用 self.cn2en1 提取相应的值
            for key in list(self.cn2en.keys())[1:]:  # 从第二个键开始，因为第一个是序号
                row.append(str(entry.get(str(self.cn2en[key]), " ")))  # 以字符串显示
            self.results_data.append(row)

        self.total_pages = total_pages
        self.total_nums = total_count
        # 更新表格数据
        self.updateTable(mode=0)

    def initialization(self, mode):
        if mode == 0:
            row_list = list(self.cn2en.keys())
            self.tableWidget_2.setColumnCount(len(row_list))
            # 设置列标题
            self.tableWidget_2.setHorizontalHeaderLabels(row_list)
            # 设置表格的大小策略
            self.tableWidget_2.setSizeAdjustPolicy(QTableWidget.AdjustToContents)
            # 允许选择整行
            self.tableWidget_2.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.updateTable(mode=1)
            # 隐藏行序号
            self.tableWidget_2.verticalHeader().setVisible(False)
            self.tableWidget_2.horizontalHeader().setVisible(False)
            # 点击第一列的cell实现改变复选框的状态
            self.tableWidget_2.cellClicked.connect(self.toggle_checkbox)
        elif mode == 1:
            row_list = list(self.cn2en1.keys())
            print(len(row_list))
            self.tableWidget.setColumnCount(len(row_list))
            # 设置列标题
            self.tableWidget.setHorizontalHeaderLabels(row_list)
            # 设置表格的大小策略
            self.tableWidget.setSizeAdjustPolicy(QTableWidget.AdjustToContents)
            # 允许选择整行
            self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.updateTable2(mode=0)
            # 隐藏行序号
            self.tableWidget.verticalHeader().setVisible(False)
            self.tableWidget.horizontalHeader().setVisible(False)

    def updateTable2(self, mode=1):
        if mode == 1:
            self.ckxf()
        # 清空表格中的现有数据
        for row in range(self.tableWidget.rowCount()):
            for column in range(self.tableWidget.columnCount()):
                self.tableWidget.setItem(row, column, QTableWidgetItem(""))

        # 截取数据
        page_data = self.results_data
        tableWidget = self.tableWidget
        tableWidget.setRowCount(int(self.comboBox_10.currentText()) + 1)  # + 1的原因是除开第一行的表头

        # # 创建一个列表来存储复选框
        self.checkboxes = []
        font = QFont("微软雅黑", 10)  # 字体为 微软雅黑，大小为 10
        tableWidget.setFont(font)
        # 先把表头加入
        for idx, header_name in enumerate(list(self.cn2en1.keys())):
            item = QTableWidgetItem(header_name)
            item.setTextAlignment(Qt.AlignCenter)
            item.setFlags(item.flags() & ~Qt.ItemIsEditable)
            item.setFont(QFont("微软雅黑", 10, QFont.Bold))
            item.setBackground(QColor("#d3d3d3"))
            tableWidget.setItem(0, idx, item)

        for row in range(int(self.comboBox_10.currentText())):
            try:
                for column in range(len(page_data[row])):
                    label_size = 12
                    if column == 9:
                        if page_data[row][column] == "1":
                            label = QLabel()
                            label.setPixmap(self.pixmapT)
                            label.setScaledContents(True)
                            label.setFixedSize(label_size, label_size)
                            label.setAlignment(Qt.AlignCenter)  # 居中对齐
                            label_layout = QHBoxLayout()
                            label_layout.addWidget(label)
                            label_layout.setContentsMargins(0, 0, 0, 0)  # 去除边距以紧凑显示
                            cell_widget = QWidget()
                            cell_widget.setLayout(label_layout)
                            tableWidget.setCellWidget(row + 1, column, cell_widget)
                        elif page_data[row][column] == "0":
                            label = QLabel()
                            label.setPixmap(self.pixmapF)
                            label.setScaledContents(True)
                            label.setFixedSize(label_size, label_size)
                            label.setAlignment(Qt.AlignCenter)  # 居中对齐
                            label_layout = QHBoxLayout()
                            label_layout.addWidget(label)
                            label_layout.setContentsMargins(0, 0, 0, 0)  # 去除边距以紧凑显示
                            cell_widget = QWidget()
                            cell_widget.setLayout(label_layout)
                            tableWidget.setCellWidget(row + 1, column, cell_widget)
                    # 检查第七列的内容
                    if page_data[row][column] == "已完成":  # 假设第七列的索引是 6
                        item = QTableWidgetItem(page_data[row][column])
                        item.setForeground(QColor("green"))  # 将文字颜色设置为绿色
                        item.setTextAlignment(Qt.AlignCenter)
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                        tableWidget.setItem(row + 1, column, item)
                    elif page_data[row][column] == "已阅失败" or page_data[row][column] == "复阅不一致":
                        item = QTableWidgetItem(page_data[row][column])
                        item.setForeground(QColor("red"))  # 将文字颜色设置为绿色
                        item.setTextAlignment(Qt.AlignCenter)
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                        tableWidget.setItem(row + 1, column, item)
                    else:
                        item = QTableWidgetItem(page_data[row][column])
                        item.setTextAlignment(Qt.AlignCenter)
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                        tableWidget.setItem(row + 1, column, item)

            except Exception as e:
                for column in range(len(list(self.cn2en1.keys()))):
                    item = QTableWidgetItem("")
                    item.setTextAlignment(Qt.AlignCenter)
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    # 移除上一页残留的进度条和详情
                    tableWidget.removeCellWidget(row + 1, column)
                    tableWidget.setItem(row + 1, column, item)

        try:
            if self.page_number == int(self.pushButton_35.text()):
                self.pushButton_40.setStyleSheet("""
                            QPushButton {
                                font: 10pt "微软雅黑";
                                border-radius: 1px;
                            }
                        """)
                self.pushButton_43.setStyleSheet("""
                            QPushButton {
                                font: 10pt "微软雅黑";
                                border-radius: 1px;
                            }
                        """)
                self.pushButton_35.setStyleSheet("background-color: " + self.bcolor + ";")
            elif self.page_number == int(self.pushButton_43.text()):
                self.pushButton_40.setStyleSheet("""
                            QPushButton {
                                font: 10pt "微软雅黑";
                                border-radius: 1px;
                            }
                        """)
                self.pushButton_35.setStyleSheet("""
                            QPushButton {
                                font: 10pt "微软雅黑";
                                border-radius: 1px;
                            }
                        """)
                self.pushButton_43.setStyleSheet("background-color: " + self.bcolor + ";")
            elif self.page_number == int(self.pushButton_40.text()):
                self.pushButton_43.setStyleSheet("""
                            QPushButton {
                                font: 10pt "微软雅黑";
                                border-radius: 1px;
                            }
                        """)
                self.pushButton_35.setStyleSheet("""
                            QPushButton {
                                font: 10pt "微软雅黑";
                                border-radius: 1px;
                            }
                        """)
                self.pushButton_40.setStyleSheet("background-color: " + self.bcolor + ";")
            else:
                self.pushButton_35.setText("1")
                self.pushButton_40.setText("2")
                self.pushButton_43.setText("3")
                self.pushButton_40.setStyleSheet("""
                            QPushButton {
                                font: 10pt "微软雅黑";
                                border-radius: 1px;
                            }
                        """)
                self.pushButton_43.setStyleSheet("""
                            QPushButton {
                                font: 10pt "微软雅黑";
                                border-radius: 1px;
                            }
                        """)
                self.pushButton_35.setStyleSheet("background-color: " + self.bcolor + ";")

        except:
            pass
        self.check_right_left()
        self.check_three()

    def updateTable(self, mode=1):
        if mode == 1:
            self.select_data_first()
        # 截取数据
        page_data = self.results_data
        print(page_data,"@@@@@@@@@@")
        print(self.total_pages, self.total_nums,"---------------------------------------")
        self.label_12.setText(f"共{self.total_nums}条/{self.total_pages}页")
        tableWidget_2 = self.tableWidget_2
        tableWidget_2.setRowCount(int(self.comboBox_10.currentText()) + 1)  # + 1的原因是除开第一行的表头
        # # 创建一个列表来存储复选框
        self.checkboxes = []
        font = QFont("微软雅黑", 10)  # 字体为 微软雅黑，大小为 10
        tableWidget_2.setFont(font)
        # 先把表头加入
        for idx, header_name in enumerate(list(self.cn2en.keys())):
            item = QTableWidgetItem(header_name)
            item.setTextAlignment(Qt.AlignCenter)
            item.setFlags(item.flags() & ~Qt.ItemIsEditable)
            item.setFont(QFont("微软雅黑", 10, QFont.Bold))
            item.setBackground(QColor("#d3d3d3"))
            tableWidget_2.setItem(0, idx, item)

        self.button1_list = []
        for row in range(int(self.comboBox_10.currentText())):
            if (self.page_number - 1) * self.items_per_page + row + 1 <= len(self.now_data):
                checkbox = QCheckBox()  # 设置父级为表格
                self.checkboxes.append(checkbox)  # 存储复选框
                checkbox_layout = QHBoxLayout()  # Create a horizontal layout
                checkbox_layout.addWidget(checkbox, alignment=Qt.AlignCenter)  # Align center
                checkbox_layout.setContentsMargins(0, 0, 0, 0)  # Remove margins to keep it tight
                # Set layout to the cell widget
                cell_widget = QWidget()
                cell_widget.setLayout(checkbox_layout)
                self.tableWidget_2.setCellWidget(row + 1, 0, cell_widget)
            else:
                item = QTableWidgetItem("")
                item.setTextAlignment(Qt.AlignCenter)
                item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                self.tableWidget_2.setItem(row + 1, 0, item)
            try:
                for column in range(len(page_data[row])):
                    if column == len(page_data[row]) - 1:  # 最后一行
                        button = QPushButton("详情")
                        button.setFont(font)
                        button.setStyleSheet("""
                            QPushButton {
                                color: #5673E5;     /* 字体颜色 */
                                border: none;     /* 去掉边框 */
                            }
                            QPushButton:hover {
                                background-color: gray;  /* 悬停时的背景颜色 */
                            }
                        """)
                        button.clicked.connect(
                            partial(self.jump_page, page_data[row][1], page_data[row][4], page_data[row][3]))
                        tableWidget_2.setCellWidget(row + 1, column, button)
                        continue

                    if column == len(page_data[row]) - 2:  # 倒数第二列
                        button1 = QPushButton("阅卷")
                        button1.setFont(font)

                        # 设置字体、颜色和去掉边框，以及禁用状态下的颜色
                        button1.setStyleSheet("""
                            QPushButton {
                                color: #5673E5;     /* 字体颜色 */
                                border: none;       /* 去掉边框 */
                            }
                            QPushButton:hover {
                                background-color: gray;  /* 悬停时的背景颜色 */
                            }
                            QPushButton:disabled {
                                color: gray;       /* 禁用时的字体颜色 */
                                background-color: lightgray; /* 禁用时的背景颜色 */
                            }
                        """)

                        # 将按钮添加到列表中
                        self.button1_list.append(button1)

                        button1.clicked.connect(
                            partial(self.on_score_button_clicked, page_data[row][1], page_data[row][3],
                                    page_data[row][4], row + 1))
                        tableWidget_2.setCellWidget(row + 1, column, button1)

                    # 检查第七列的内容
                    if page_data[row][column] == "已完成":  # 假设第七列的索引是 6
                        item = QTableWidgetItem(page_data[row][column])
                        item.setForeground(QColor("green"))  # 将文字颜色设置为绿色
                        item.setTextAlignment(Qt.AlignCenter)
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                        tableWidget_2.setItem(row + 1, column, item)
                    elif page_data[row][column] == "已阅失败" or page_data[row][column] == "复阅不一致":
                        item = QTableWidgetItem(page_data[row][column])
                        item.setForeground(QColor("red"))  # 将文字颜色设置为绿色
                        item.setTextAlignment(Qt.AlignCenter)
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                        tableWidget_2.setItem(row + 1, column, item)
                    elif page_data[row][column] == "None":  # 如果内容为 None
                        item = QTableWidgetItem("")  # 显示空白
                        item.setTextAlignment(Qt.AlignCenter)
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                        tableWidget_2.setItem(row + 1, column, item)
                    else:
                        item = QTableWidgetItem(page_data[row][column])
                        item.setTextAlignment(Qt.AlignCenter)
                        item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                        tableWidget_2.setItem(row + 1, column, item)

            except Exception as e:
                for column in range(len(list(self.cn2en.keys()))):
                    item = QTableWidgetItem("")
                    item.setTextAlignment(Qt.AlignCenter)
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    # 移除上一页残留的进度条和详情
                    tableWidget_2.removeCellWidget(row + 1, column)
                    tableWidget_2.setItem(row + 1, column, item)
        # 创建表头复选框
        self.header_checkbox = QCheckBox()
        self.header_checkbox.setFont((QFont("微软雅黑", 10, QFont.Bold)))
        checkbox_layout = QHBoxLayout()  # Create a horizontal layout
        checkbox_layout.addWidget(self.header_checkbox, alignment=Qt.AlignCenter)  # Align center
        checkbox_layout.setContentsMargins(0, 0, 0, 0)  # Remove margins to keep it tight
        # Set layout to the cell widget
        cell_widget = QWidget()
        cell_widget.setLayout(checkbox_layout)
        self.tableWidget_2.setCellWidget(0, 0, cell_widget)
        # 连接信号和槽
        self.header_checkbox.stateChanged.connect(lambda: self.on_header_checkbox_state_changed(self.header_checkbox.isChecked()))

        try:
            if self.page_number == int(self.pushButton_35.text()):
                self.pushButton_40.setStyleSheet("""
                    QPushButton {
                        font: 10pt "微软雅黑";
                        border-radius: 1px;
                    }
                """)
                self.pushButton_43.setStyleSheet("""
                    QPushButton {
                        font: 10pt "微软雅黑";
                        border-radius: 1px;
                    }
                """)
                self.pushButton_35.setStyleSheet("background-color: " + self.bcolor + ";")
            elif self.page_number == int(self.pushButton_43.text()):
                self.pushButton_40.setStyleSheet("""
                    QPushButton {
                        font: 10pt "微软雅黑";
                        border-radius: 1px;
                    }
                """)
                self.pushButton_35.setStyleSheet("""
                    QPushButton {
                        font: 10pt "微软雅黑";
                        border-radius: 1px;
                    }
                """)
                self.pushButton_43.setStyleSheet("background-color: " + self.bcolor + ";")
            elif self.page_number == int(self.pushButton_40.text()):
                self.pushButton_43.setStyleSheet("""
                    QPushButton {
                        font: 10pt "微软雅黑";
                        border-radius: 1px;
                    }
                """)
                self.pushButton_35.setStyleSheet("""
                    QPushButton {
                        font: 10pt "微软雅黑";
                        border-radius: 1px;
                    }
                """)
                self.pushButton_40.setStyleSheet("background-color: " + self.bcolor + ";")
            else:
                self.pushButton_35.setText("1")
                self.pushButton_40.setText("2")
                self.pushButton_43.setText("3")
                self.pushButton_40.setStyleSheet("""
                    QPushButton {
                        font: 10pt "微软雅黑";
                        border-radius: 1px;
                    }
                """)
                self.pushButton_43.setStyleSheet("""
                    QPushButton {
                        font: 10pt "微软雅黑";
                        border-radius: 1px;
                    }
                """)
                self.pushButton_35.setStyleSheet("background-color: " + self.bcolor + ";")

        except:
            pass
        self.check_right_left()
        self.check_three()



    def check_right_left(self):
        # *** 实现页码自适应宽度展示 ***
        self.pushButton_35.setMinimumWidth(max(30, 10 * len(str(int(self.pushButton_35.text())))))
        self.pushButton_35.setMaximumWidth(max(30, 10 * len(str(int(self.pushButton_35.text())))))
        self.pushButton_40.setMinimumWidth(max(30, 10 * len(str(int(self.pushButton_40.text())))))
        self.pushButton_40.setMaximumWidth(max(30, 10 * len(str(int(self.pushButton_40.text())))))
        self.pushButton_43.setMinimumWidth(max(30, 10 * len(str(int(self.pushButton_43.text())))))
        self.pushButton_43.setMaximumWidth(max(30, 10 * len(str(int(self.pushButton_43.text())))))
        #
        # # self.total_pages = (len(self.now_data) + self.items_per_page - 1) // self.items_per_page
        self.pushButton_44.setEnabled(self.page_number < self.total_pages)
        self.pushButton_34.setEnabled(self.page_number > 1)
        
    def check_three(self):
        # 禁用按钮如果超出范围
        # print(self.total_pages)

        self.pushButton_35.setEnabled(int(self.pushButton_35.text()) <= self.total_pages)
        self.pushButton_40.setEnabled(int(self.pushButton_40.text()) <= self.total_pages)
        self.pushButton_43.setEnabled(int(self.pushButton_43.text()) <= self.total_pages)

    def previousPage(self):
        if self.page_number > 1:
            self.page_number -= 1
            self.updatePageButtons(mode=-1)
            if self.pushButton_25.text() == "查看详分":
                self.updateTable()
            elif self.pushButton_25.text() == "返回":
                self.updateTable2()
        self.check_right_left()

    def nextPage(self):
        if (self.page_number + 1) * self.items_per_page < self.total_nums or (self.page_number + 1) * self.items_per_page >= self.total_nums\
                and self.page_number * self.items_per_page < self.total_nums:
            self.page_number += 1
            self.updatePageButtons(mode=1)
            if self.pushButton_25.text() == "查看详分":
                self.updateTable()
            elif self.pushButton_25.text() == "返回":
                self.updateTable2()
        self.check_right_left()

    def updatePageButtons(self, mode):
        # 更新按钮文本
        if mode == 1:
            first_num = int(self.pushButton_35.text())
            if first_num + 2 < self.total_pages:
                self.pushButton_35.setText(str(first_num + 1))
                self.pushButton_40.setText(str(first_num + 2))
                self.pushButton_43.setText(str(first_num + 3))
        elif mode == -1:
            first_num = int(self.pushButton_43.text())
            if first_num > 3:
                self.pushButton_35.setText(str(first_num - 3))
                self.pushButton_40.setText(str(first_num - 2))
                self.pushButton_43.setText(str(first_num - 1))

        self.check_right_left()
    
    def changePage(self, page_index):
        if page_index == 0:
            self.page_number = int(self.pushButton_35.text())
        elif page_index == 1:
            self.page_number = int(self.pushButton_40.text())
        elif page_index == 2:
            self.page_number = int(self.pushButton_43.text())

        if self.pushButton_25.text() == "查看详分":
            self.updateTable()
        elif self.pushButton_25.text() == "返回":
            self.updateTable2()
        self.check_right_left()
        self.check_three()

    def update_data(self):
        if self.comboBox_2.currentText() == "":
            self.comboBox_2.setItemText(0, "请选择科目")
            self.check_first = 1
            return
        self.setupUI()


    # 定义复选框状态改变时的槽函数
    def on_header_checkbox_state_changed(self, cur_state):
        # 更新所有复选框的状态
        for idx, checkbox in enumerate(self.checkboxes):
            if (self.page_number - 1) * self.items_per_page + idx + 1 <= self.total_nums:
                checkbox.setChecked(cur_state)

    def toggle_checkbox(self, row, column):
        if column == 0:  # 如果点击的是第一列
            if row == 0: # 特判：全选框
                if self.header_checkbox.isChecked():
                    self.header_checkbox.setChecked(False)
                else:
                    self.header_checkbox.setChecked(True)
                return
            try:
                item = self.checkboxes[row - 1]
                print(item.isChecked())
                if item.isChecked():
                    item.setChecked(False)
                else:
                    item.setChecked(True)
            except IndexError as e:
                print(e)

    # 重置阅卷状态按钮响应函数
    def reset(self):
        start_index = self.items_per_page
        end_index = start_index + self.items_per_page
        states = [checkbox.isChecked() for checkbox in self.checkboxes]
        # print(states)
        # 获取值为 True 的索引 (即：需要上传的用户)
        true_indices = [index for index, state in enumerate(states) if state]
        for idx in true_indices:
            # print(idx)
            page_data = self.now_data[idx]
            # print(page_data)
            paper_id = page_data["paper_id"]
            subject_code = page_data["subject_code"]
            student_id = page_data["student_id"]
            parent_answer_id = page_data["answer_id"]
            # 读取设置文件
            self.settings_file = getdir() + 'api/ConfigJson.txt'
            with open(self.settings_file, 'r', encoding='utf-8') as file:
                settings = json.load(file)
            exam_year = settings["year"]
            cursor.execute(
                "SELECT paper_no, exam_year FROM exam_subject_student WHERE paper_id = ? AND subject_code = ? AND student_id = ?",
                (paper_id, subject_code, student_id))
            results = cursor.fetchone()
            paper_no = results[0]

            self.Mark_initial(exam_year,student_id, paper_id, subject_code, parent_answer_id, paper_no)

            item = QTableWidgetItem("未阅")
            item.setForeground(QColor("black"))  # Set text color to red
            item.setTextAlignment(
                Qt.AlignCenter | Qt.AlignVCenter)  # Center horizontally and vertically
            item.setFlags(item.flags() & ~Qt.ItemIsEditable)  # Make the item non-editable
            self.tableWidget_2.setItem(idx + 1, 7, item)

        QMessageBox.information(self, "信息", "状态已重置")


    def Marking_error(self, exam_year, student_id, paper_id, subject_code, parent_answer_id, paper_no):

        # 根据给定的字段更新split_answer_status为2
        cursor.execute("""
               UPDATE exam_scan_split
               SET split_answer_status = 2
               WHERE exam_year = ? AND student_id = ? AND paper_id = ? AND subject_code = ? AND answer_id = ?
           """, (exam_year, student_id, paper_id, subject_code, parent_answer_id))
        # 提交事务
        db_manager.connection.commit()

        # 根据给定的字段更新split_answer_status为2
        cursor.execute("""
               UPDATE exam_subject_paper_initialize
               SET split_answer_check_status = 2
               WHERE exam_year = ? AND student_id = ? AND paper_id = ? AND subject_code = ? AND answer_id = ? AND paper_no = ?
           """, (exam_year, student_id, paper_id, subject_code, parent_answer_id, paper_no))
        # 提交事务
        db_manager.connection.commit()

    def Mark_correctly(self, exam_year, student_id, paper_id, subject_code, parent_answer_id, paper_no):
        # 根据给定的字段更新split_answer_status为1
        cursor.execute("""
               UPDATE exam_scan_split
               SET split_answer_status = 1
               WHERE exam_year = ? AND student_id = ? AND paper_id = ? AND subject_code = ? AND answer_id = ?
           """, (exam_year, student_id, paper_id, subject_code, parent_answer_id))
        # 提交事务
        db_manager.connection.commit()

        # 根据给定的字段更新split_answer_status为1
        cursor.execute("""
               UPDATE exam_subject_paper_initialize
               SET split_answer_check_status = 1
               WHERE exam_year = ? AND student_id = ? AND paper_id = ? AND subject_code = ? AND answer_id = ? AND paper_no = ?
           """, (exam_year, student_id, paper_id, subject_code, parent_answer_id, paper_no))
      # 提交事务
        db_manager.connection.commit()

    def Mark_initial(self, exam_year, student_id, paper_id, subject_code, parent_answer_id, paper_no):
        # 根据给定的字段更新split_answer_status为1
        cursor.execute("""
               UPDATE exam_scan_split
               SET split_answer_status = 0
               WHERE exam_year = ? AND student_id = ? AND paper_id = ? AND subject_code = ? AND answer_id = ?
           """, (exam_year, student_id, paper_id, subject_code, parent_answer_id))
        # 提交事务
        db_manager.connection.commit()

        # 根据给定的字段更新split_answer_status为1
        cursor.execute("""
               UPDATE exam_subject_paper_initialize
               SET split_answer_check_status = 1
               WHERE exam_year = ? AND student_id = ? AND paper_id = ? AND subject_code = ? AND answer_id = ? AND paper_no = ?
           """, (exam_year, student_id, paper_id, subject_code, parent_answer_id, paper_no))
      # 提交事务
        db_manager.connection.commit()

    def on_score_button_clicked(self, subject_code, answer_qr_code, student_id, row):
        """启动阅卷线程"""
        print(subject_code, answer_qr_code, student_id, row)
        # 禁用所有阅卷按钮
        for button in self.button1_list:
            print(button,str(button), "禁用")
            button.setEnabled(False)
        self.scoring_thread = ScoringThread(subject_code, answer_qr_code, student_id, row, self)
        self.scoring_thread.scoring_done_signal.connect(self.on_scoring_done)
        self.scoring_thread.start()

    def on_scoring_done(self, row, message):
        """阅卷完成后的处理"""
        print(f"阅卷完成，行号：{row}")
        if message == "fail":
            item = QTableWidgetItem("已阅失败")
            item.setForeground(QColor("red"))  # Set text color to red
            item.setTextAlignment(
                Qt.AlignCenter | Qt.AlignVCenter)  # Center horizontally and vertically
            item.setFlags(item.flags() & ~Qt.ItemIsEditable)  # Make the item non-editable
            self.tableWidget_2.setItem(row, 7, item)
        elif message == "success":
            item = QTableWidgetItem("已完成")
            item.setForeground(QColor("green"))  # Set text color to green
            item.setTextAlignment(
                Qt.AlignCenter | Qt.AlignVCenter)  # Center horizontally and vertically
            item.setFlags(item.flags() & ~Qt.ItemIsEditable)  # Make the item non-editable
            self.tableWidget_2.setItem(row, 7, item)
        # 在这里更新 UI 或执行其他操作
        QMessageBox.information(self, "信息", "该考生阅卷完成")
        # 启用所有阅卷按钮
        for button in self.button1_list:
            print(button,str(button), "启用")
            button.setEnabled(True)

    def switch(self):
        print("响应")
        self.initialization(mode=0)
        self.updateTable(mode=0)
        self.stackedWidget.setCurrentIndex(1)

    def handle_result(self, result):
        # 在主线程中处理线程返回的结果
        print("处理结果：", result)
        # 更新UI组件
        self.update_table(result)

    def handle_error(self, error_msg):
        # 在主线程中处理线程中发生的错误
        QMessageBox.critical(self, "错误", error_msg)

    def select(self):
        subject = self.comboBox_2.currentText()
        keyword = self.lineEdit_4.text()
        split_answer_status = self.comboBox_4.currentText()

        if split_answer_status == "阅卷状态":
            split_answer_status = ""
        elif split_answer_status == "未阅":
            split_answer_status = 0
        elif split_answer_status == "已完成":
            split_answer_status = 1
        elif split_answer_status == "已阅失败":
            split_answer_status = 2

        self.select_thread = SelectThread(subject, keyword, split_answer_status, self.page_number, self.items_per_page,
                                          self)
        self.select_thread.data_signal.connect(self.update_table1)
        self.select_thread.data2_signal.connect(self.update_table2)
        self.select_thread.start()

    def update_table1(self, results_data, total_pages, total_count):
        self.results_data = results_data
        self.total_pages = total_pages
        self.total_nums = total_count
        self.updateTable(mode=0)

    def update_table2(self, results_data, total_pages, total_count):
        self.results_data = results_data
        self.total_pages = total_pages
        self.total_nums = total_count
        self.updateTable2(mode=0)

    def calculate_scores(self, answers):
        # 初始化一个字典来存储每个大题的得分情况
        score_dict = {}

        # 遍历答题数据
        for subject_code, exam_number, candidate_number, question_group, question_number, correct_answer, student_answer, score in answers:
            # 确保 score 是整数
            if score is not None:
                score = int(score)

            # 创建一个唯一的键来标识每个大题
            key = (subject_code, exam_number, question_number, candidate_number)

            # 如果大题不在字典中，初始化它的得分
            if key not in score_dict:
                score_dict[key] = {
                    'paper_id': exam_number,
                    'subject_code': subject_code,
                    'answer_id': question_number,
                    'student_id': candidate_number,
                    'total_score': 0
                }

            # 如果学生答案正确，则累加分数
            if student_answer == correct_answer and isinstance(score, int):
                score_dict[key]['total_score'] += score

        # 将字典的值转换为列表
        return list(score_dict.values())

    def jump_page(self, subject_code, student_id, answer_qr_code):

        self.pushButton_25.setText("返回")
        # 更改按钮功能，连接到新的槽函数
        self.pushButton_25.clicked.disconnect()  # 断开原来的连接
        self.pushButton_25.clicked.connect(self.goBack)  # 连接到新的槽函数

        print(subject_code,student_id,answer_qr_code)
        # 提取第一位和第二位
        question_type = answer_qr_code.split("、")[1]  # 第一位代表题目类型
        section_number = answer_qr_code.split("、")[0]  # 第二位代表大题号
        if question_type == "单选题":
            question_type = "1"
        elif question_type == "多选题":
            question_type = "2"
        elif question_type == "判断题":
            question_type = "3"

        # 转换第二位为中文大写数字
        converted_section_number = self.convert_chinese_to_arabic(section_number)
        # 组合新的值
        new_value = f"{question_type}{converted_section_number}"

        # 准备字典来存储 subject_code 和 subject_name 的映射关系
        cursor.execute("SELECT subject_code, subject_name FROM exam_subject WHERE subject_code = ?", (subject_code))
        subject_dict = {row[0]: row[1] for row in cursor.fetchall()}

        cursor.execute("SELECT student_id, student_name FROM student_info WHERE student_id = ?", (student_id))
        student_dic = {row[0]: row[1] for row in cursor.fetchall()}

        cursor.execute("SELECT answer_id, answer_no, answer_qr_code FROM exam_answer_into WHERE answer_qr_code = ?", (new_value))
        small_question_dic = {row[0]: (row[1], row[2]) for row in cursor.fetchall()}
        print(small_question_dic)
        cursor.execute(
            "SELECT paper_id, subject_code, student_id, answer_id, answer_standard, answer_student, answer_score, modify_time FROM exam_scan_split_answer WHERE subject_code = ? AND student_id = ?", (subject_code, student_id))
        rows = cursor.fetchall()
        for row in rows:
            if row[7] is not None:
                row[7] = row[7].strftime('%Y-%m-%d %H:%M:%S')
            elif row[7] is None:
                row[7] = " "

        # 字段名列表
        field_names = [
            "paper_id", "subject_code", "student_id", "answer_id", "answer_standard", "answer_student", "answer_score",
            "modify_time",
            "subject_name", "student_name", "answer_no", "answer_qr_code", "evaluate_results", "get_score"
        ]

        # 步骤 2: 使用每个 row 的 subject_code 去第二个表里查对应的 subject_name 并添加到每个 row 里
        new_rows = []
        for row in rows:
            subject_code = row[1]
            subject_name = subject_dict.get(subject_code, "Null")
            new_row = list(row) + [subject_name]  # 将 subject_name 添加到 row
            if new_row[5] == 0:
                new_row[5] = "未阅"
            elif new_row[5] == 1:
                new_row[5] = "已完成"
            elif new_row[5] == 2:
                new_row[5] = "已阅失败"
            new_rows.append(new_row)
        self.detail_data = []
        # 再次循环 new_rows 来添加 student_name 和 answer_score
        # 过滤掉那些在small_question_dic中不存在的answer_id对应的记录
        filtered_rows = [
            new_row for new_row in new_rows
            if new_row[3] in small_question_dic
        ]

        # 现在filtered_rows只包含那些answer_id存在于small_question_dic中的记录
        for new_row in filtered_rows:
            student_id = new_row[2]
            student_name = student_dic.get(student_id, "Null")
            answer_id = new_row[3]
            answer_no, answer_qr_code = small_question_dic[answer_id]
            student_row = new_row + [student_name, answer_no, answer_qr_code]

            if student_row[5] == student_row[4]:
                get_score = student_row[6]
                evaluate_results = "1"
            else:
                get_score = "0"
                evaluate_results = "0"

            finally_row = student_row + [evaluate_results, get_score]

            # 提取第一位和第二位
            question_type = finally_row[11][0]  # 第一位代表题目类型
            section_number = finally_row[11][1]  # 第二位代表大题号
            if question_type == "1":
                question_type = "单选题"
            elif question_type == "2":
                question_type = "多选题"
            elif question_type == "3":
                question_type = "判断题"

            # 转换第二位为中文大写数字
            converted_section_number = self.convert_section_number(section_number)

            # 组合新的值
            new_value = f"{converted_section_number}、{question_type}"
            finally_row[11] = new_value  # 更新 new_row[3] 的值

            # 创建一个字典来存储字段名和对应的值
            row_dict = dict(zip(field_names, finally_row))
            # print(row_dict)
            self.detail_data.append(row_dict)

        self.results_data = []
        for index, entry in enumerate(self.detail_data, start=1):
            row = [str((self.page_number - 1) * self.items_per_page + index)]  # 序号
            # 使用 self.cn2en1 提取相应的值
            for key in list(self.cn2en1.keys())[1:]:  # 从第二个键开始，因为第一个是序号
                row.append(str(entry.get(str(self.cn2en1[key]), " ")))  # 以字符串显示
            self.results_data.append(row)

        print(self.results_data)
        self.initialization(mode=1)
        self.updateTable2(mode=0)
        self.stackedWidget.setCurrentIndex(0)

class DetailThread(QThread):
    """用于处理详分数据的线程"""
    detail_data_signal = pyqtSignal(list, int, int)  # 信号传递数据和总页数

    def __init__(self, page_number, items_per_page, parent=None):
        super().__init__(parent)
        self.page_number = page_number
        self.items_per_page = items_per_page

    def run(self):
        """线程运行时执行的函数"""
        # 准备字典来存储 subject_code 和 subject_name 的映射关系
        cursor.execute("SELECT subject_code, subject_name FROM exam_subject")
        subject_dict = {row[0]: row[1] for row in cursor.fetchall()}

        cursor.execute("SELECT student_id, student_name FROM student_info")
        student_dic = {row[0]: row[1] for row in cursor.fetchall()}

        cursor.execute("SELECT answer_id, answer_no, answer_qr_code FROM exam_answer_into")
        small_question_dic = {row[0]: (row[1], row[2]) for row in cursor.fetchall()}

        # 计算分页的起始和结束索引
        offset = (self.page_number - 1) * self.items_per_page
        limit = self.items_per_page

        # 查询总记录数
        cursor.execute("SELECT COUNT(*) FROM exam_scan_split_answer")
        total_count = cursor.fetchone()[0]
        total_pages = (total_count + self.items_per_page - 1) // self.items_per_page

        # 使用 ROW_NUMBER() 实现分页
        query = """
        WITH Paginated AS (
            SELECT 
                paper_id, subject_code, student_id, answer_id, answer_standard, answer_student, answer_score, modify_time,
                ROW_NUMBER() OVER (ORDER BY student_id) AS row_num
            FROM exam_scan_split_answer
        )
        SELECT paper_id, subject_code, student_id, answer_id, answer_standard, answer_student, answer_score, modify_time
        FROM Paginated
        WHERE row_num BETWEEN ? AND ?
        """
        start_row = offset + 1
        end_row = offset + limit
        cursor.execute(query, (start_row, end_row))
        rows = cursor.fetchall()
        for row in rows:
            if row[7] is not None:
                row[7] = row[7].strftime('%Y-%m-%d %H:%M:%S')
            elif row[7] is None:
                row[7] = " "

        # 字段名列表
        field_names = [
            "paper_id", "subject_code", "student_id", "answer_id", "answer_standard", "answer_student",
            "answer_score", "modify_time",
            "subject_name", "student_name", "answer_no", "answer_qr_code", "evaluate_results", "get_score"
        ]

        detail_data = []
        for row in rows:
            subject_code = row[1]
            subject_name = subject_dict.get(subject_code, "Null")
            student_id = row[2]
            student_name = student_dic.get(student_id, "Null")
            answer_id = row[3]
            answer_no, answer_qr_code = small_question_dic.get(answer_id, ("Null", "Null"))

            if row[5] == row[4]:
                get_score = row[6]
                evaluate_results = "1"
            else:
                get_score = "0"
                evaluate_results = "0"

            # 提取第一位和第二位
            question_type = answer_qr_code[0]  # 第一位代表题目类型
            section_number = answer_qr_code[1]  # 第二位代表大题号
            if question_type == "1":
                question_type = "单选题"
            elif question_type == "2":
                question_type = "多选题"
            elif question_type == "3":
                question_type = "判断题"

            # 转换第二位为中文大写数字
            converted_section_number = self.convert_section_number(section_number)

            # 组合新的值
            new_value = f"{converted_section_number}、{question_type}"

            # 创建一个字典来存储字段名和对应的值
            row_dict = {
                "paper_id": row[0],
                "subject_code": subject_code,
                "student_id": student_id,
                "answer_id": row[3],
                "answer_standard": row[4],
                "answer_student": row[5],
                "answer_score": row[6],
                "modify_time": row[7],
                "subject_name": subject_name,
                "student_name": student_name,
                "answer_no": answer_no,
                "answer_qr_code": new_value,
                "evaluate_results": evaluate_results,
                "get_score": get_score
            }
            detail_data.append(row_dict)

        # 将数据和总页数通过信号发送到主线程
        self.detail_data_signal.emit(detail_data, total_pages, total_count)

    def convert_section_number(self, section_number):
        """将数字转换为中文大写数字"""
        chinese_numbers = {
            '1': '一', '2': '二', '3': '三', '4': '四',
            '5': '五', '6': '六', '7': '七', '8': '八',
            '9': '九', '10': '十'
        }
        return chinese_numbers.get(section_number, '')

class FirstDetailThread(QThread):
    """用于处理详分数据的线程"""
    data_signal = pyqtSignal(list, int, int, list)  # 信号传递数据和总页数

    def __init__(self, page_number, items_per_page, parent=None):
        super().__init__(parent)
        self.page_number = page_number
        self.items_per_page = items_per_page

    def run(self):
        """线程运行时执行的函数"""
        offset = (self.page_number - 1) * self.items_per_page
        limit = self.items_per_page

        # 查询总记录数
        cursor.execute("SELECT COUNT(*) FROM exam_scan_split WHERE answer_qr_code LIKE '1%' OR answer_qr_code LIKE '2%' OR answer_qr_code LIKE '3%'")
        total_count = cursor.fetchone()[0]
        total_pages = (total_count + self.items_per_page - 1) // self.items_per_page

        # 使用 ROW_NUMBER() 实现分页
        query = """
        WITH Paginated AS (
            SELECT 
                paper_id, subject_code, student_id, answer_id, answer_qr_code, split_answer_status, modify_time,
                ROW_NUMBER() OVER (ORDER BY student_id) AS row_num
            FROM exam_scan_split
            WHERE answer_qr_code LIKE '1%' OR answer_qr_code LIKE '2%' OR answer_qr_code LIKE '3%'
        )
        SELECT paper_id, subject_code, student_id, answer_id, answer_qr_code, split_answer_status, modify_time
        FROM Paginated
        WHERE row_num BETWEEN ? AND ?
        """
        start_row = offset + 1
        end_row = offset + limit
        cursor.execute(query, (start_row, end_row))
        rows = cursor.fetchall()

        # 准备字典来存储 subject_code 和 subject_name 的映射关系
        cursor.execute("SELECT subject_code, subject_name FROM exam_subject")
        subject_dict = {row[0]: row[1] for row in cursor.fetchall()}

        cursor.execute("SELECT student_id, student_name FROM student_info")
        student_dic = {row[0]: row[1] for row in cursor.fetchall()}

        cursor.execute("SELECT answer_id, child_num, answer_score FROM exam_answer_into WHERE child_num != 0")
        question_dic = {row[0]: (row[1], row[2]) for row in cursor.fetchall()}

        cursor.execute("SELECT subject_code, paper_id, student_id, answer_id, parent_answer_id, answer_standard, answer_student, answer_score FROM exam_scan_split_answer")
        studentscore_dic = cursor.fetchall()
        scores_dict = self.calculate_scores(studentscore_dic)

        # 字段名列表
        field_names = [
            "paper_id", "subject_code", "student_id", "answer_id", "answer_qr_code",
            "split_answer_status", "modify_time", "subject_name", "student_name",
            "child_num", "answer_score"
        ]
        data = []
        # 处理分页数据
        new_rows = []
        for row in rows:
            subject_code = row[1]
            subject_name = subject_dict.get(subject_code, "Null")
            new_row = list(row) + [subject_name]  # 将 subject_name 添加到 row
            if new_row[5] == 0:
                new_row[5] = "未阅"
            elif new_row[5] == 1:
                new_row[5] = "已完成"
            elif new_row[5] == 2:
                new_row[5] = "已阅失败"
            new_rows.append(new_row)

        # 再次循环 new_rows 来添加 student_name 和 answer_score
        for new_row in new_rows:
            student_id = new_row[2]
            student_name = student_dic.get(student_id, "Null")
            answer_id = new_row[3]
            child_num, answer_score = question_dic.get(answer_id, ("Null", "Null"))
            student_row = new_row + [student_name, child_num, answer_score]  # 将 student_name 和 answer_score 添加到 new_row

            # 提取第一位和第二位
            question_type = student_row[4][0]  # 第一位代表题目类型
            section_number = student_row[4][1]  # 第二位代表大题号
            if question_type == "1":
                question_type = "单选题"
            elif question_type == "2":
                question_type = "多选题"
            elif question_type == "3":
                question_type = "判断题"

            # 转换第二位为中文大写数字
            converted_section_number = self.convert_section_number(section_number)

            # 组合新的值
            new_value = f"{converted_section_number}、{question_type}"
            student_row[4] = new_value  # 更新 new_row[3] 的值
            # 创建一个字典来存储字段名和对应的值
            row_dict = dict(zip(field_names, student_row))

            data.append(row_dict)

        # 发送信号
        self.data_signal.emit(data, total_pages, total_count, scores_dict)

    def convert_section_number(self, section_number):
        """将数字转换为中文大写数字"""
        chinese_numbers = {
            '1': '一', '2': '二', '3': '三', '4': '四',
            '5': '五', '6': '六', '7': '七', '8': '八',
            '9': '九', '10': '十'
        }
        return chinese_numbers.get(section_number, '')

    def calculate_scores(self, answers):
        # 初始化一个字典来存储每个大题的得分情况
        score_dict = {}

        # 遍历答题数据
        for subject_code, exam_number, candidate_number, question_group, question_number, correct_answer, student_answer, score in answers:
            # 确保 score 是整数
            if score is not None:
                score = int(score)

            # 创建一个唯一的键来标识每个大题
            key = (subject_code, exam_number, question_number, candidate_number)

            # 如果大题不在字典中，初始化它的得分
            if key not in score_dict:
                score_dict[key] = {
                    'paper_id': exam_number,
                    'subject_code': subject_code,
                    'answer_id': question_number,
                    'student_id': candidate_number,
                    'total_score': 0
                }

            # 如果学生答案正确，则累加分数
            if student_answer == correct_answer and isinstance(score, int):
                score_dict[key]['total_score'] += score

        # 将字典的值转换为列表
        return list(score_dict.values())